import java.io.File;

import org.tmatesoft.sqljet.core.SqlJetException;
import org.tmatesoft.sqljet.core.SqlJetTransactionMode;
import org.tmatesoft.sqljet.core.table.ISqlJetCursor;
import org.tmatesoft.sqljet.core.table.ISqlJetTable;
import org.tmatesoft.sqljet.core.table.SqlJetDb;

public class DatabseAdapter implements IDatabase {
	private static final String DB_NAME = "db.sqlite";
	Chapter chapter;
	Verse verse;

	@Override
	public void addVerse(Book book) throws SqlJetException {
		File dbFile = new File(DB_NAME);
		SqlJetDb db = SqlJetDb.open(dbFile, true);

		// System.out.println();
		// System.out.println(">Database schema objects:");
		// System.out.println();
		// System.out.println(db.getSchema());
		// System.out.println(db.getOptions());

		// insert rows:
		db.beginTransaction(SqlJetTransactionMode.WRITE);
		try {
			ISqlJetTable table = db.getTable("VERSE");
			for (Chapter chapter : book.chapters) {
				this.chapter = chapter;
				for (Verse verse : chapter.getVerses()) {
					this.verse = verse;

					try {
						table.insert(book.name, chapter.getNumber(),
								verse.number, verse.content);
					} catch (Exception e) {
						System.out.println(book.name + " "
								+ chapter.getNumber() + ":" + verse.number);// TODO:
																			// handle
																			// exception
					}
				}
			}

		}

		finally {
			db.commit();
		}
	}

	@Override
	public void addBook(Book book) throws SqlJetException {

		File dbFile = new File(DB_NAME);
		SqlJetDb db = SqlJetDb.open(dbFile, true);

		// insert rows:
		db.beginTransaction(SqlJetTransactionMode.WRITE);
		try {
			ISqlJetTable table = db.getTable("BOOK");
			table.insert(book.name, book.name);

		} finally {
			db.commit();
		}

	}

	private void print() throws SqlJetException {
		File dbFile = new File(DB_NAME);
		SqlJetDb db = SqlJetDb.open(dbFile, true);
		// insert rows:
		db.beginTransaction(SqlJetTransactionMode.WRITE);
		try {
			ISqlJetTable table = db.getTable("verse");
			printRecords(table.order(table.getPrimaryKeyIndexName()).reverse());

		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			db.commit();
		}

	}

	private static void printRecords(ISqlJetCursor cursor)
			throws SqlJetException {
		try {
			if (!cursor.eof()) {
				do {
					String x = cursor.getString(3);
					System.out.println(cursor.getString(0) + " "
							+ cursor.getString(1) + " " + cursor.getInteger(2)
							+ ":" + cursor.getString(3));
				} while (cursor.next());
			}
		} finally {
			cursor.close();
		}
	}

	public static void main(String[] args) throws SqlJetException {
		DatabseAdapter db = new DatabseAdapter();
		db.print();
	}

}
